package com.zhouyu.exampleThread.threadTest;

import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * Description:CompletableFuture测试
 *
 * @author zhouyu
 * @create 2020/7/21
 */
@Log4j2
@Component
public class CompletableFutureTest {

    public static void main(String[] args) {
        CompletableFutureTest futureTest = new CompletableFutureTest();
        try {
            futureTest.supplyAsyncNotify();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @Author zhouyu
     * @Description Future 计算完成后自动回调通知并返回结果
     * @date 2020/7/21 16:14
     */
    public void supplyAsyncNotify() {
        try {
            CompletableFuture<String> sleepCompletableFuture = CompletableFuture.supplyAsync(() -> {
                //可以注释掉做快速返回 start
                log.info("0:{}",Thread.currentThread().getName());
                return  "洗澡;";
            }).thenApply(first -> {
                log.info("1:{}",Thread.currentThread().getName());
                return first + "擦干净;";
            }).thenApplyAsync(second -> {
                log.info("2:{}",Thread.currentThread().getName());
                return second + "睡觉";
            });
            log.info("3:{}",Thread.currentThread().getName());
            String result = sleepCompletableFuture.get();
            log.info("result:{}", result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }

    /**
     * @Author zhouyu
     * @Description 异步任务回调通知，但是回调不需要返回结果
     * @date 2020/7/21 17:00
     */
    public void supplyAsyncNoReturns() {
        CompletableFuture.supplyAsync(() -> {
            return "我是一个异步任务";
        }).thenAccept(result -> {
            log.info("{}，结束了", result);
        });
    }

    public void notifyAsync(){
        CompletableFuture<String> stringCompletableFuture = CompletableFuture.supplyAsync(() -> {
            log.info("前序操作");
            return "前需操作结果1";
        }).thenApplyAsync(result -> {
            log.info("后续操作");
            return "后续操作结果2";
        });
    }

}